package com.websever.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/*
 线程任务
 负责与特定的客户端进行HTTP交互
 */
public class ClientHandler implements Runnable {
   private Socket socket;
   public ClientHandler(Socket socket){
       this.socket = socket;
   }

    public void run() {
        try {
            // 解析请求

            InputStream inp = socket.getInputStream();
            StringBuilder builder = new StringBuilder();
            char cur = 'a';
            char pre = 'a';
            int d1;
            while ((d1 = inp.read())!=-1){
                cur = (char)d1;
                if (pre == 13 && cur == 10){
                    break;
                }
                builder.append(cur);
                pre = cur;
            }
            String line = builder.toString().trim();
            System.out.println("请求行"+line);
            //请求相关信息
            String method;//请求方式
            String uri;//抽象路径
            String protocol;//协议版本
            String [] data = line.split("\\s");
            method =data[0];
            uri =data[1];
            protocol =data[2];
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);


            // 处理请求
            // 发送相应
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //响应后断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
